var abitur = {};

function showPopover(directObject, messageText, position, html, title)
{
  position = position || 'right';
  html = html || false;
  title = title || 'Внимание!';
  directObject.popover('destroy');
  directObject.popover({'trigger':'manual','html':html,'content':messageText,'title': title,'placement':position});
  directObject.popover('show');
  setTimeout(function(){directObject.popover('hide');},3000);
}


function addAbiturientChange(valueObj)
{
   var disc = $('#i_discipline').val();

   if (valueObj[disc] == undefined)
       $.ajax({
           url: base_url+'abiturient/getDiscInfo',
           async:false,
           type: 'POST',
           dataType: 'json',
           data: {id : disc},
           success:function(data) 
           {
               valueObj[disc] = data;
           }
       });

   if (valueObj[disc]['pAbout'] != '')
      $('.aboutDiscipline').html('<p>' + valueObj[disc]['pAbout'] + '</p>');
   else
       $('.aboutDiscipline').html("Данные о специальности отсутствуют");

   $('.disciplinesEge').html('');
   if (typeof valueObj[disc].exam == 'object')
   {
      for (i in valueObj[disc].exam)
      {
         $('.disciplinesEge').append("<tr><td>" + valueObj[disc].exam[i].discName +  "</td>" + "<td>" + valueObj[disc].exam[i].pValue + "</td>"+"<td>" + parseInt(Math.random()*100) + "</td>"+"</tr>" );
      }
   }
}

function bindAction()
{
     $('.editAbiturient').click(function(){   
        var id = $(this).data('id');

        if (abitur[id] == undefined)
        {
            $.ajax({
               url: base_url+'abiturient/getAbiturientById',
               async: false,
               type: 'POST',
               dataType: 'json',
               data: {id: id},
               success: function(data)
               {
                  if (!data.err)
                  {
                     abitur[id] = data;
                     console.log(data);
                     $('#id').val(data.id);
                     $('#famModal').val(data.pFamily);
                     $('#nameModal').val(data.pName);
                     $('#discIdModal').val(data.tDiscipline);
                     $('#cityIdModal').val(data.tCity);
                     $('#adressModal').val(data.pAdress);
                     $('#phoneModal').val(data.pPhone);  
                  }
                  else
                  {
                     alert(data.text);
                  }
               }
            });
        }
            $('#editAbiturientModal').modal('show');

    });

   $('.saveAbiturient').click(function(){ 

      if ($('#id').val() == '')
      {
         $.ajax({
            url: base_url+'abiturient/save',
            async: false,
            type: 'POST',
            dataType: 'json',
            data: {
               pFamily     : $('#famModal').val(), 
               pName       : $('#nameModal').val(), 
               tDiscipline : $('#discIdModal').val(),
               tCity       : $('#cityIdModal').val(),
               pAdress     : $('#adressModal').val(),
               pPhone     : $('#phoneModal').val()
            },
            success: function(data)
            {
               $('#editAbiturientModal').modal('hide');
               if (typeof data.err == undefined)
                  return false;
            }
         });
      }
      else
      {
         $.ajax({
            url: base_url+'abiturient/save/true',
            async: false,
            type: 'POST',
            dataType: 'json',
            data: {
               id          : $('#id').val(),
               pFamily     : $('#famModal').val(), 
               pName       : $('#nameModal').val(), 
               tDiscipline : $('#discIdModal').val(),
               tCity       : $('#cityIdModal').val(),
               pAdress     : $('#adressModal').val(),
               pPhone      : $('#phoneModal').val()
            },
            success: function(data)
            {
               $('#editAbiturientModal').modal('hide');
               location.reload();
            }
         });
      }
   });

}

$(document).ready(function(){
   var valueObj = {};

   bindAction();
   addAbiturientChange(valueObj);


   var disc = $('#i_discipline').val();
   $.ajax({
      url: base_url+'abiturient/getDiscInfo',
      async: false,
      type: 'POST',
      dataType: 'json',
      data: {id : disc},
      success:function(data) 
      {
          valueObj[disc] = data;
      }
   });
 //  $('.aboutDiscipline').html(valueObj[disc]['pAbout']); 

   $('#i_discipline').change(
        function(){
            addAbiturientChange(valueObj);
        }
    );

    $('#discId, #cityId').change(
        function(){
            var disc = $('#discId').val();
            var city = $('#cityId').val();

            var filtrs = {};
            $.each($("div.control-group").find("select"), function(key, val){
                filtrs[$(val).attr("name")] = $(val).val(); 
            });

            for (var key in filtrs)
            {
                if (filtrs[key] =='')
                    delete filtrs[key];
            }

            console.log(filtrs);
            $.ajax({
                url: base_url+'abiturient/getAbiturientByFiltr/',
                async: false,
                type: 'POST',
                dataType: 'json',
                data: filtrs, //фильтры отправляем
                success:function(data)
                {
                    valueObj[disc] = data;         
                }
            });
           // console.log(valueObj[disc]);
            if (valueObj[disc] == '')
                $('#abiturientsCont').html("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
            else
                $('#abiturientsCont').html(_.template($('#trTempl').html(), {abiturient:valueObj[disc]}));
            bindAction();
        }
    );

    $('#addAbiturient').click(function(){
        $('#editAbiturientModal').modal('show');

        if ($(this).data('id')==undefined)
        {
            $('#myModalLabel').text('Добавление абитуриента');
        }
    });


    $('#addAbiturVacansy').click(function(){
        // $('#addAbiturVacansy').popover('show');
        var tDisc = $('#i_discipline').val();
        $.ajax({
            url: base_url+'abiturient/checkAbiturForAdd/',
            async: false,
            type: 'POST',
            dataType: 'json',
            data: {'tDisc' : tDisc},
            success:function(data)
            { 
                if (data.err == 1)
                        showPopover(
                            $('#addAbiturVacansy'),
                            data.text,
                            'right',
                            true
                        );

                if (data.status == 'ok')
                    showPopover(
                            $('#addAbiturVacansy'),
                            'Дисциплина успешно добавлена в список',
                            'right',
                            true
                        );
            }
        });
    });

    
});